package com.alan.cueencoding.api;

import com.alan.cueencoding.dto.ConvertDTO;
import com.alan.cueencoding.error.NoneCueFileExtensionSupportException;
import com.alan.cueencoding.service.CueEncodingService;
import com.alan.cueencoding.util.MatchingResult;
import com.alan.cueencoding.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Alan.xiao
 * @date 2022/10/3
 */
@Slf4j
@Controller
@CrossOrigin
public class CueEncodingFacade {

    private static final String CUE_FILE_EXTENSION = "cue";

    @Resource
    CueEncodingService cueEncodingService;


    /**
     * 跳转至使用页
     *
     * @param request
     * @return
     */
    @RequestMapping("/")
    public String home(HttpServletRequest request) {
        return "facade";
    }

    /**
     * 跳转至使用页
     *
     * @param request
     * @return
     */
    @RequestMapping("/cue/index")
    public String facade(HttpServletRequest request) {
        return "facade";
    }


    /**
     * 上传cue文件并进行编码匹配检测的处理
     *
     * @param file
     * @return
     */
    @RequestMapping("/cue/file/upload")
    @ResponseBody
    public Result<List<MatchingResult>> uploadFile(@RequestPart("file") MultipartFile file) {
        Assert.notNull(file, "file must not be null.");

        if (!file.getOriginalFilename().contains(CUE_FILE_EXTENSION)) {
            throw new NoneCueFileExtensionSupportException();
        }

        List<MatchingResult> matchingResults = cueEncodingService.processEncoding(file);
        return Result.success(matchingResults);
    }


    @RequestMapping(value = "/cue/file/convertAndDownload")
    @ResponseBody
    public void convertAndDownload(@RequestBody ConvertDTO convertDTO) {
        cueEncodingService.convertAndDownload(convertDTO);
    }
}
